import config from "../config/index";

let cacheToken = "";
const NOT_HTTP_CODE_LIST=['ZXJC_SESSION/token']
function request(url, method, data, showLoading) {
  if (showLoading) {
    wx.showLoading({
      title: "加载中...",
    });
  }

  let headers = {
      "Content-Type": "application/x-www-form-urlencoded",
      token: cacheToken,
    },
    fixUrl = `${config.baseUrl}${
      url.startsWith("/") ? "" : "/ZXJC_USER/"
    }${url}`;

  //返回一个Promise对象
  return new Promise(function (resolve, reject) {
    wx.setStorageSync(
      "token_over_time",
      new Date().getTime() + 1000 * 60 * 60 * 2
    );

    wx.request({
      url: fixUrl, // 测试
      method: method,
      data: data,
      header: headers,
      success: function (res) {
        wx.hideLoading();
        //这里可以根据自己项目服务端定义的正确的返回码来进行，接口请求成功后的处理，当然也可以在这里进行报文加解密的统一处理
        if (res.data) {
          if (res.data.httpCode == "403") {
            login();
          } else if (res.data.httpCode == "401") {
            getToken();
          } else if (res.data.httpCode == "0") {
            // wx.showToast({
            //   title: res.data.message,
            //   icon: "none",
            // });
          }else  if (res.data.httpCode===200) {
            resolve(res.data);
          } else {
            // wx.showModal({
            //   title: "提示",
            //   content: res.data.msg,
            //   confirmColor: "#118EDE",
            //   showCancel: false,
            //   success: function (res) {
            //     if (res.confirm) {
            //       reject(res.data);
            //     }
            //   },
            // });
            if(res.data.success){
                resolve(res.data)
            }else{
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000//持续的时间
            })
            reject(res.data);
        }
          }
        } else {
          //如果出现异常则弹出dialog
          // wx.showModal({
          //   title: "提示",
          //   content: res.data.errCode + "系统异常",
          //   confirmColor: "#118EDE",
          //   showCancel: false,
          //   success: function (res) {
          //     if (res.confirm) {
          //       reject(res.data);
          //     }
          //   },
          // });
          wx.showToast({
            title: res.data.errCode + "系统异常",
            icon: 'none',
            duration: 2000//持续的时间
          })
          reject(res.data);
        }
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: "服务器无法连接",
          icon: "loading",
          duration: 2000,
        });
        reject(res);
      },
    });
  });
}

let logining = false;

// 登录
function login() {
  const app = getApp();
  if (logining) {
    return;
  }

  logining = true;
  wx.login({
    success(cres) {
      wx.ajax
        .post("login.action", { code: cres.code })
        .then((res) => {
          logining = false;
          if (res.success) {
            app.globalData.userInfo = res.result; //用户sessionkey & openid
            wx.setStorageSync('userInfo', JSON.stringify(res.result))
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 1];
            // console.log(prevPage);
            if (prevPage.route == "pages/user/user") {
              prevPage.onShow();
            } else if (prevPage.route == "pages/accept-invitation/accept-invitation") {
              // 分享链接进入时 登录后调用用户关联接口
              prevPage.requestSaveSpeadInfo();
            } else if (prevPage.route != 'pages/index/index'){
              prevPage.onLoad(prevPage.options);
            }
          } else {
            wx.showToast({
              title: res.msg,
              duration: 2000,
              icon: "none",
            });
          }
        })
        .catch(() => {
          logining = false;
        });
    },
    fail(res) {
      console.log(res);
    },
  });
}

function initToken() {
  let token = wx.getStorageSync("token");
  let token_over_time = wx.getStorageSync("token_over_time");
  let thisTimestamp = new Date().getTime(); // 当前时间戳
  if (!token || thisTimestamp > token_over_time) {
    // 如果token存储已经超过2h
    getToken();
  } else {
    cacheToken = token;
  }
}

function getToken() {
    console.log('=============333333333=')
  request("/ZXJC_SESSION/token", "post", null, false).then((res) => {
    let token = res.result.token;
    cacheToken = token;
    console.log(res,'==============')
    wx.setStorageSync("token", token);
    wx.setStorageSync(
      "token_over_time",
      new Date().getTime() + 1000 * 60 * 60 * 2
    );
    login();
  });
}

function uploadFile({ filePath, fileName, callback }) {
  wx.uploadFile({
    url: `${config.uploadUrl}/ZXJC_FILE/fileUploadServlet`,
    filePath: filePath,
    name: fileName || "file",
    success: (res) => {
      const data = JSON.parse(res.data);
      if (data.success) {
        const result = data.result;

        callback && callback(result[0]);
      }
    },
  });
}

 //initToken();

wx.ajax = {
  request,
  initToken,
  getToken,
  login,
  uploadFile,
  get(url, params, showLoading) {
    return request(url, "get", params, showLoading);
  },
  post(url, data, showLoading) {
    return request(url, "post", data, showLoading);
  },
};

export default wx.ajax;
